<template>
  <div class="shareGroupWapper">
    <rj-modal
      :title="$t('groupOperate.sharetitle')"
      :visible="shareModalVisible"
      :maskClosable="false"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form-model
        :model="form"
        layout="horizontal"
        :labelCol="{ span: 6 }"
        :wrapperCol="{ span: 16 }"
      >
        <a-form-model-item :label="$t('groupOperate.sharename')">
          <a-radio-group v-model="form.authType" style="margin-top: 6px">
            <a-radio class="authItem" :value="3" name="userAuthority">{{
              $t('groupOperate.sharetipname')
            }}</a-radio>
            <p class="itemDesc">{{ $t('groupOperate.namedetail') }}</p>
            <a-radio class="authItem" :value="1" name="userAuthority">{{
              $t('groupOperate.readname')
            }}</a-radio>
            <p class="itemDesc">
              {{ $t('groupOperate.readnamedetail') }}
            </p>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item :label="$t('groupOperate.date')">
          <a-select
            :value="valiDateType"
            @change="handleValidChange"
            style="width: 120px"
          >
            <a-select-option
              :value="item.value"
              :key="item.value"
              v-for="item in valiTimeType"
            >
              {{ item.type }}
            </a-select-option>
          </a-select>
          <a-date-picker
            v-if="valiDateType == ''"
            :placeholder="$t('groupOperate.datachange')"
            :disabled-date="disabledDate"
            :disabled-time="disabledDateTime"
            :show-time="{ format: 'HH:mm:ss' }"
            @change="dateOnChange"
            @ok="selectSaveDate"
            @openChange="canceDataPick"
            :value="custorTime"
          />
          <p class="validateTimeRange">{{ validateTimeRange }}</p>
        </a-form-model-item>
      </a-form-model>
    </rj-modal>
    <ShareUrl
      v-if="showShareUrl"
      :groupInfo="groupInfo"
      :operation="operation"
      :expiredAt="expiredAt"
      @closeCallback="closeShareUrlCallBack"
    />
  </div>
</template>

<script>
import { RjModal } from '@components';
import moment from 'moment';
import ShareUrl from '../shareGroup/shareUrl.vue';
import i18nMixin from '@mixin/i18n-mixin';
import { valiTimeType } from './valiTimeType';
import { maccApi, requestHttp } from '@utils/index';
export default {
  name: 'ShareGroup',
  mixins: [i18nMixin],
  props: {
    groupInfo: {
      type: Object,
      require: true,
    },
    // alreadyUserList: {
    //   type: Array,
    // },
  },
  data() {
    return {
      alreadyUserId: [],
      subAccountList: [],
      shareModalVisible: true,
      // valiTimeType:valiTimeType,
      form: {
        authType: 3,
      },
      valiDateType: 'forever',
      custorTime: new Date().Format('YYYY-MM-DD 23:59:59'),
      validateTimeRange: this.$t('groupOperate.timeneding'),
      timeStr: new Date('2038-01-01 23:59:59'),
      showShareGroup: false,
      operation: null,
      expiredAt: null,
      showShareUrl: false,
    };
  },
  computed: {
    valiTimeType() {
      valiTimeType.forEach((item) => {
        item.type = this.$t(`groupOperate.${item.index}`);
      });
      return valiTimeType;
    },
  },
  mounted() {
    this.getSubUserList();
  },
  components: {
    'rj-modal': RjModal,
    ShareUrl,
  },
  watch: {
    valiDateType(type) {
      let now = new Date();
      let YY = now.getFullYear();
      let MM = now.getMonth() + 1;
      let dd = now.getDate();
      let hh = now.getHours();
      let mm = now.getMinutes();
      let ss = now.getSeconds();
      let adjective = '';
      switch (type) {
        case 'forever':
          this.validateTimeRange = this.$t('groupOperate.timeforever');
          this.timeStr = new Date('2038-01-01 23:59:59');
          return;
        case 1:
          adjective = new Date(+new Date(now) + type * 3600 * 24 * 1000); //不能直接将dd直接+1,因为有可能是最后一天
          this.timeStr = adjective.Format('YYYY-MM-dd 23:59:59');
          break;
        case 7:
          adjective = new Date(+new Date(now) + type * 3600 * 24 * 1000);
          this.timeStr = adjective.Format('YYYY-MM-dd 23:59:59');
          break;
        case 30:
          MM++;
          adjective = new Date(
            YY + '-' + MM + '-' + dd + ' ' + hh + ':' + mm + ':' + ss
          );
          this.timeStr = adjective.Format('YYYY-MM-dd 23:59:59');
          break;
        case 365:
          YY++;
          adjective = new Date(
            YY + '-' + MM + '-' + dd + ' ' + hh + ':' + mm + ':' + ss
          );
          this.timeStr = adjective.Format('YYYY-MM-dd 23:59:59');
          break;
        case '':
          this.timeStr = new Date().Format('YYYY-MM-dd 23:59:59');
          this.custorTime = new Date().Format('YYYY-MM-DD 23:59:59');
          break;
      }
      this.validateTimeRange = `${this.$t('groupOperate.timetoending')}${
        this.timeStr
      }`;
    },
  },
  methods: {
    handleOk() {
      // this.$emit('closeCallback', {
      //   operation: this.form.authType,
      //   expiredAt: new Date(this.timeStr).getTime(),
      // });
      // this.$emit('closeCallback');
      this.shareModalVisible = false;
      this.$nextTick(() => {
        this.showShareUrl = true;
        this.operation = this.form.authType;
        this.expiredAt = new Date(this.timeStr).getTime();
        //  this.$emit('closeCallback');
      });
    },
    handleCancel() {
      this.$emit('closeCallback');
    },

    //获取子账号列表
    async getSubUserList() {
      const { code, msg, accountList = [] } = await requestHttp({
        api: `${maccApi.GET_SUB_USER_LIST_API}?page_index=1&page_size=999`,
        method: 'GET',
      });
      if (code == 0) {
        this.subAccountList = accountList.filter((item) => {
          console.log(this.alreadyUserId);
          return this.alreadyUserId.indexOf(item.id) == -1;
        });
      } else {
        this.$message.error(msg || this.$t('groupOperate.getchildrenlist'));
      }
    },
    handleValidChange(value) {
      this.valiDateType = value;
    },
    dateOnChange(value) {
      this.timeStr = value.format('YYYY-MM-DD HH:mm:ss');
      this.custorTime = value.format('YYYY-MM-DD HH:mm:ss');
    },
    selectSaveDate(value) {
      const timeVal = value.format('YYYY-MM-DD HH:mm:ss');
      this.validateTimeRange = `${this.$t(
        'groupOperate.timetoending'
      )}${timeVal}`;
    },
    canceDataPick(status) {
      if (!status) {
        //点击空白关闭时
        const timeVal = moment(this.custorTime).format('YYYY-MM-DD HH:mm:ss');
        this.validateTimeRange = `${this.$t(
          'groupOperate.timetoending'
        )}${timeVal}`;
      }
    },
    disabledDate(current) {
      console.log('current', current);
      console.log('moment', moment().endOf('day'));
      return current && current < moment().add(0, 'day');
    },

    //关闭分享链接弹窗
    closeShareUrlCallBack() {
      this.showShareUrl = false;
      this.$emit('closeCallback');
    },

    disabledDateTime(current) {
      const selectYear = current.year();
      const selectMonth = current.month() + 1;
      const selectDate = current.dates();
      const selectHour = current.hours();
      const selectMinute = current.minute();
      // const selectSecond = current(newTime).second();
      const newTime = +new Date();
      const nowYear = moment(newTime).year();
      const nowMonth = moment(newTime).month() + 1;
      const nowDate = moment(newTime).dates();
      const nowHour = moment(newTime).hours();
      const nowMinute = moment(newTime).minute();
      const nowSecond = moment(newTime).second();
      if (
        selectYear > nowYear ||
        selectMonth > nowMonth ||
        selectDate > nowDate
      ) {
        return;
      } else if (selectDate == nowDate) {
        //如果选中的是当前
        //过滤出当前时间之前的时间，设置为不可选
        const rangeHours = this.range(0, 23).filter((item) => {
          return item < nowHour;
        });
        const rangeMinutes = this.range(0, 60).filter((item) => {
          if (selectHour == nowHour) {
            return item < nowMinute;
          }
        });
        const rangeSeconeds = this.range(0, 60).filter((item) => {
          if (selectMinute == nowMinute) {
            return item < nowSecond;
          }
        });
        return {
          disabledHours: () => rangeHours, //设置不可选的
          disabledMinutes: () => rangeMinutes,
          disabledSeconds: () => rangeSeconeds,
        };
      }
    },
    range(start, end) {
      const result = [];
      for (let i = start; i < end; i++) {
        result.push(i);
      }
      return result;
    },
  },
};
</script>

<style lang="less" scoped>
.itemDesc {
  color: #ccc;
  margin: 5px 0 5px 0;
}
.validateTimeRange {
  color: #abcdef;
}
</style>
